# 开发人员：萌狼蓝天
# 博客：Https://mllt.cc
# 笔记：Https://cnblogs.com/mllt
# 哔哩哔哩/微信公众号：萌狼蓝天
# 开发时间：2022/5/1
# Coding：UTF-8
import time
import game_sprites as gsp
import pygame
# 游戏固定参数
class GameSet:
    window_title = "飞翔的小鸟" + "@萌狼工作室"
    window_width = 800
    window_height = 600
    game_fps = 120
    game_clock = pygame.time.Clock()  # Clock时钟对象，以确保游戏以所设定的FPS运行
    game_background = pygame.image.load("img/background.jpg")
# 游戏颜色
class GameColor:
    color_user_background = (47, 64, 86)
    color_font_tips = (1, 170, 237)
    color_background = (238, 238, 238)
# 创建窗口
def game_window(WINDOW_width, WINDOW_height, WINDOW_title):
    """
    创建窗口
    :param WINDOW_width:窗口宽度
    :param WINDOW_height:窗口高度
    :param WINDOW_title:窗口标题
    :return:screen | <class 'pygame.Surface'>
    """
    pygame.init()  # Pygame模块初始化
    screen = pygame.display.set_mode((WINDOW_width, WINDOW_height))  # 创建游戏窗口
    pygame.display.set_caption(WINDOW_title)  # 设置窗口标题栏文字
    return screen
# 添加精灵到精灵组
def game_addElfToElfs(elfs, elf):
    """
    通过此函数获得障碍物精灵组
    :param elfs:要加入的精灵组
    :param elf:需要添加的精灵对象
    :return:新的精灵组
    """
    elfs.add(elf)
    return elfs
# 更新精灵组
def game_elfsUpdate(elfs, screen):
    """
    通过此函数更新精灵组并绘制到窗口上
    :param elfs:精灵组
    :param screen:窗口
    :return:无返回值
    """
    elfs.update()
    elfs.draw(screen)
# 文字图片
def game_font(text, size=14, color=(0, 0, 0), font="fonts/fang_zheng_kai_ti_GBK.ttf"):
    text_font = pygame.font.Font(font, size)  # (文本内容，字体大小) 建议自己设置字体避免中文显示问题
    text_img = text_font.render(text, True, color)
    return text_img


def game_playing(gameset, val_screen):
    # 基本
    pygame.init()  # Pygame模块初始化
    var_running = True  # 设置游戏状态为启动
    var_end = False  # 设置程序状态为未结束
    while not var_end:
        var_time_start = time.time()  # 获取系统当前时间，记录为开始运行时间
        var_count = 0  # 运行后刷新的帧数。用于计算帧率   # 帧数/时间 = 每秒多少帧
        var_time_last = var_time_start
        var_nandu = 0
        elfs_user = pygame.sprite.Group()  # 创建精灵组(Elf Group)
        elfs_obs = pygame.sprite.Group()  # 创建精灵组(Elf Group)
        # 玩家对象
        user = gsp.User("img/bird.png", gameset.window_width, gameset.window_height, 100,
                        gameset.window_height / 2, 0,
                        5)
        game_addElfToElfs(elfs_user, user)
        # 游戏进行体
        result = 0  # 分数重置
        while var_running:
            gameset.game_clock.tick(gameset.game_fps)  # 设置帧率（tick告诉pygame一秒执行多少次）
            for event in pygame.event.get():  # pygame内部保存自上一帧以来发生的所有事件
                if event.type == pygame.QUIT:  # 用户点击关闭按钮
                    var_running=False
                    var_end=True
            # 计算帧率
            var_count += 1
            var_time_now = time.time()
            timec = (var_time_now - var_time_start)
            var_fps = int(var_count / timec)
            c = var_time_now - var_time_last
            if c >= var_nandu:
                result += 1
                ob = gsp.Obstacle("img/pillar.png", gameset.window_width, gameset.window_height / 2, -100, 100)
                elfs_obs = game_addElfToElfs(elfs_obs, ob)
                var_time_last = time.time()
                # var_nandu = 0.75
                var_nandu = 0.5
            # 画面更新
            val_screen.blit(gameset.game_background, (0, 0))  # 背景加载
            val_screen.blit(game_font("FPS:" + str(int(var_fps))+"当前分数："+str(result)), (0, 0))  # FPS显示
            game_elfsUpdate(elfs_user, val_screen)  # 玩家更新
            game_elfsUpdate(elfs_obs, val_screen)  # 障碍物更新
            pygame.display.flip()  # 翻转（类似刷新，但不是刷新）屏幕
            # 碰撞检测
            for i in elfs_obs:
                if not pygame.sprite.collide_mask(user, i) is None:
                    var_running = False
                    pygame.display.flip()  # 翻转（类似刷新，但不是刷新）屏幕
        # 来到这一步的时候，说明撞到柱子了，开始显示分数，询问是否继续
        # 重新开始游戏
        for i in elfs_obs:
            i.kill()
        for i in elfs_user:
            i.kill()
        game_elfsUpdate(elfs_user, val_screen)
        game_elfsUpdate(elfs_obs, val_screen)

        game_fail(gameset, val_screen, result)
    # pygame.quit()
# 窗口失败界面
def game_fail(gameset, val_screen, result):
    # 基本
    pygame.init()  # Pygame模块初始化
    # 预设参数
    var_end = False
    while not var_end:
        gameset.game_clock.tick(gameset.game_fps)  # 设置帧率（tick告诉pygame一秒执行多少次）
        val_screen.blit(gameset.game_background, (0, 0))  # 背景加载
        text_result = game_font("游戏结束，您获得的分数为{}".format(result), 45, (255, 255, 255))
        text_restart = game_font("重来".format(result), 35, (255, 255, 255))
        text_main = game_font("回到主页".format(result), 35, (255, 255, 255))
        val_screen.blit(text_result, (gameset.window_width / 2 - text_result.get_rect().width / 2, 100))
        val_screen.blit(text_restart, (gameset.window_width / 2 - text_restart.get_rect().width / 2, 200))
        val_screen.blit(text_main, (gameset.window_width / 2 - text_main.get_rect().width / 2, 300))
        pygame.display.flip()
        for event in pygame.event.get():  # pygame内部保存自上一帧以来发生的所有事件
            if event.type == pygame.QUIT:  # 用户点击关闭按钮
                var_end=True
            if event.type == pygame.MOUSEBUTTONDOWN:
                x = pygame.mouse.get_pos()[0]
                y = pygame.mouse.get_pos()[1]
                print(x, y)
                xc = int(gameset.window_width / 2)
                if y >= 200:
                    if y < 300:
                        if x > xc - int(text_restart.get_width() / 2):
                            if x < int(xc + text_restart.get_width() / 2):
                                game_playing(gameset, val_screen)
                    if y < text_main.get_height() + 300:
                        if x > xc - int(text_main.get_width() / 2):
                            if x < int(xc + text_main.get_width() / 2):
                                game_main()
    pygame.quit()
# 窗口主界面，通向运行
def game_main():
    # 基本
    pygame.init()  # Pygame模块初始化
    # 预设参数
    var_end = False
    gameset = GameSet()
    # 窗口创建
    val_screen = game_window(gameset.window_width, gameset.window_height, gameset.window_title)
    while not var_end:
        gameset.game_clock.tick(gameset.game_fps)  # 设置帧率（tick告诉pygame一秒执行多少次）
        val_screen.blit(pygame.image.load("img/background.jpg"), (0, 0))  # 背景加载
        text_game_title = game_font(" 飞翔的小鸟", 45, (255, 255, 255))
        text_game_start = game_font(" -- 开始游戏 --", 35, (255, 255, 255))
        # text_game_exit = game_font(" -- 退出游戏 --", 35, (255, 255, 255))
        val_screen.blit(text_game_title, (gameset.window_width / 2 - text_game_title.get_rect().width / 2, 100))
        val_screen.blit(text_game_start, (gameset.window_width / 2 - text_game_start.get_rect().width / 2, 250))
        # val_screen.blit(text_game_exit, (gameset.window_width / 2 - text_game_exit.get_rect().width / 2, 350))
        pygame.display.flip()  # 翻转（类似刷新，但不是刷新）屏幕
        # 设置窗口关闭功能
        for event in pygame.event.get():  # pygame内部保存自上一帧以来发生的所有事件
            if event.type == pygame.QUIT:  # 用户点击关闭按钮
                var_end = True
            if event.type == pygame.MOUSEBUTTONDOWN:
                x = pygame.mouse.get_pos()[0]
                y = pygame.mouse.get_pos()[1]
                print(x, y)
                xc = int(gameset.window_width / 2)
                yc = int(gameset.window_height / 2)
                if y >= 250:
                    if y < text_game_start.get_height() + 250:
                        if x > xc - int(text_game_start.get_width() / 2):
                            if x < int(xc + text_game_start.get_width() / 2):
                                game_playing(gameset, val_screen)
    pygame.quit()


if __name__ == '__main__':
    game_main()
